import { createSlice, PayloadAction } from '@reduxjs/toolkit';
import { Theme, TypeTheme } from '../types';
const match = matchMedia('(prefers-color-scheme: dark)');

function followOs(state: Theme) {
  let theme;
  if (match.matches) {
    theme = 'dark';
  } else {
    theme = 'light';
  }
  window.document.documentElement.setAttribute('data-theme', theme);
  document.documentElement.setAttribute('data-prefers-color-scheme', theme);
  state.mode = theme;
}

const initialState: Theme = {
  mode: 'light',
};

const themeModule = createSlice({
  name: 'theme',
  initialState,
  reducers: {
    updateTheme: (state, action: PayloadAction<TypeTheme>) => {
      let theme = action.payload;
      if (theme === 'system') {
        if (match.matches) {
          theme = 'dark';
        } else {
          theme = 'light';
        }
        match.addEventListener('change', () => followOs(state));
      } else {
        match.removeEventListener('change', () => followOs(state));
      }
      window.document.documentElement.setAttribute('data-theme', theme);
      document.documentElement.setAttribute('data-prefers-color-scheme', theme);
      state.mode = theme;
    },
  },
});

export const { updateTheme } = themeModule.actions;
export default themeModule.reducer;
